package com.l01.h264player

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.SurfaceHolder
import com.l01.h264player.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    private lateinit var mainBinding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mainBinding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(mainBinding.root)
        checkPermission()
        mainBinding.surface.holder.addCallback(callback)
    }

    private val callback = object : SurfaceHolder.Callback {
        override fun surfaceCreated(holder: SurfaceHolder) {
            val path = "${Environment.getExternalStorageDirectory().path}/h264/out.h264"
            val player = H264Player(this@MainActivity, path, holder.surface)
            player.play()
            Log.d("TAG_MainActivity", "surfaceCreated....$path")
        }

        override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
            Log.d("TAG_MainActivity", "surfaceChanged....$width * $height")
        }

        override fun surfaceDestroyed(holder: SurfaceHolder) {
            Log.d("TAG_MainActivity", "surfaceDestroyed....")
        }
    }


    private fun checkPermission(): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            requestPermissions(
                arrayOf(
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ), 1
            );

        }
        return false;
    }
}